<template>
  <div class="job-statistics">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">岗位统计</span>
          <div class="header-actions">
            <div class="auto-refresh-controls">
              <el-switch
                v-model="autoRefresh"
                @change="toggleAutoRefresh"
                active-text="自动刷新"
                inactive-text="手动刷新"
                size="small"
              />
              <el-select
                v-model="refreshInterval"
                @change="updateRefreshInterval"
                size="small"
                style="width: 100px; margin-left: 8px;"
                :disabled="!autoRefresh"
              >
                <el-option label="10秒" :value="10" />
                <el-option label="30秒" :value="30" />
                <el-option label="60秒" :value="60" />
                <el-option label="5分钟" :value="300" />
              </el-select>
            </div>
            <el-button type="primary" @click="refreshData" :loading="loading">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 统计概览 -->
      <div class="statistics-overview">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <el-statistic
                title="总岗位数"
                :value="statistics.jobs.total"
                suffix="个"
              >
                <template #prefix>
                  <el-icon style="color: #409eff"><Briefcase /></el-icon>
                </template>
              </el-statistic>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <el-statistic
                title="已发布岗位"
                :value="statistics.jobs.published"
                suffix="个"
              >
                <template #prefix>
                  <el-icon style="color: #67c23a"><Check /></el-icon>
                </template>
              </el-statistic>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <el-statistic
                title="总申请数"
                :value="statistics.applications.total"
                suffix="个"
              >
                <template #prefix>
                  <el-icon style="color: #e6a23c"><Document /></el-icon>
                </template>
              </el-statistic>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <el-statistic
                title="合作公司"
                :value="statistics.companies.total"
                suffix="家"
              >
                <template #prefix>
                  <el-icon style="color: #f56c6c"><OfficeBuilding /></el-icon>
                </template>
              </el-statistic>
            </el-card>
          </el-col>
        </el-row>

        <!-- 第二行统计卡片 -->
        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="6">
            <el-card class="stat-card">
              <el-statistic
                title="申请成功率"
                :value="statistics.applications.success_rate"
                suffix="%"
                :precision="1"
              >
                <template #prefix>
                  <el-icon style="color: #67c23a"><TrendCharts /></el-icon>
                </template>
              </el-statistic>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <el-statistic
                title="近30天新增岗位"
                :value="statistics.jobs.recent_30_days"
                suffix="个"
              >
                <template #prefix>
                  <el-icon style="color: #409eff"><Plus /></el-icon>
                </template>
              </el-statistic>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <el-statistic
                title="近30天新增申请"
                :value="statistics.applications.recent_30_days"
                suffix="个"
              >
                <template #prefix>
                  <el-icon style="color: #e6a23c"><DocumentAdd /></el-icon>
                </template>
              </el-statistic>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <el-statistic
                title="活跃公司"
                :value="statistics.companies.active_companies.length"
                suffix="家"
              >
                <template #prefix>
                  <el-icon style="color: #f56c6c"><Star /></el-icon>
                </template>
              </el-statistic>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表区域 -->
      <div class="charts-section">
        <el-row :gutter="20">
          <!-- 岗位状态分布 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <h3>岗位状态分布</h3>
              </template>
              <div ref="jobStatusChartRef" class="chart-container"></div>
            </el-card>
          </el-col>

          <!-- 申请状态分布 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <h3>申请状态分布</h3>
              </template>
              <div ref="applicationStatusChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- 岗位类型分布 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>岗位类型分布</h3>
                  <el-button type="text" @click="refreshChart('jobType')" size="small">
                    刷新
                  </el-button>
                </div>
              </template>
              <div ref="jobTypeChartRef" class="chart-container"></div>
            </el-card>
          </el-col>

          <!-- 公司类型分布 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>公司类型分布</h3>
                  <el-button type="text" @click="refreshChart('companyType')" size="small">
                    刷新
                  </el-button>
                </div>
              </template>
              <div ref="companyTypeChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 趋势分析 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>岗位发布趋势（最近30天）</h3>
                  <div class="chart-controls">
                    <el-select v-model="trendPeriod" @change="updateTrendChart" size="small">
                      <el-option label="最近7天" value="week" />
                      <el-option label="最近30天" value="month" />
                      <el-option label="最近90天" value="quarter" />
                    </el-select>
                    <el-button type="text" @click="refreshChart('trend')" size="small">
                      刷新
                    </el-button>
                  </div>
                </div>
              </template>
              <div ref="trendChartRef" class="chart-container-large"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 薪资分布和地区分布 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>薪资分布</h3>
                  <el-button type="text" @click="refreshChart('salary')" size="small">
                    刷新
                  </el-button>
                </div>
              </template>
              <div ref="salaryChartRef" class="chart-container"></div>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>热门地区</h3>
                  <el-button type="text" @click="refreshChart('location')" size="small">
                    刷新
                  </el-button>
                </div>
              </template>
              <div ref="locationChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 热门岗位和活跃公司 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>热门岗位 TOP10</h3>
                  <el-button type="text" @click="refreshChart('popular')" size="small">
                    刷新
                  </el-button>
                </div>
              </template>
              <div ref="popularJobsChartRef" class="chart-container"></div>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>活跃公司 TOP10</h3>
                  <el-button type="text" @click="refreshChart('activeCompany')" size="small">
                    刷新
                  </el-button>
                </div>
              </template>
              <div ref="activeCompanyChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 行业分布和公司规模 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>行业分布</h3>
                  <el-button type="text" @click="refreshChart('industry')" size="small">
                    刷新
                  </el-button>
                </div>
              </template>
              <div ref="industryChartRef" class="chart-container"></div>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="chart-header">
                  <h3>公司规模分布</h3>
                  <el-button type="text" @click="refreshChart('companySize')" size="small">
                    刷新
                  </el-button>
                </div>
              </template>
              <div ref="companySizeChartRef" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 详细数据表格 -->
        <el-row>
          <el-col :span="24">
            <el-card class="table-card">
              <template #header>
                <div class="table-header">
                  <h3>详细统计数据</h3>
                  <div class="table-controls">
                    <el-button type="primary" @click="exportData" size="small">
                      导出数据
                    </el-button>
                    <el-button @click="refreshData" size="small">
                      刷新
                    </el-button>
                  </div>
                </div>
              </template>

              <el-tabs v-model="activeTab" type="card">
                <el-tab-pane label="热门岗位" name="popular">
                  <el-table :data="statistics.popular_jobs" border style="width: 100%">
                    <el-table-column prop="title" label="岗位名称" />
                    <el-table-column prop="company__name" label="公司名称" />
                    <el-table-column prop="application_count" label="申请数量" sortable />
                    <el-table-column label="操作">
                      <template #default="{ row }">
                        <el-button type="text" size="small" @click="viewJobDetail(row.id)">
                          查看详情
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>

                <el-tab-pane label="活跃公司" name="active">
                  <el-table :data="statistics.companies.active_companies" border style="width: 100%">
                    <el-table-column prop="name" label="公司名称" />
                    <el-table-column prop="company_type" label="公司类型" />
                    <el-table-column prop="total_jobs" label="发布岗位" sortable />
                    <el-table-column prop="active_jobs" label="活跃岗位" sortable />
                    <el-table-column prop="total_applications" label="收到申请" sortable />
                    <el-table-column label="操作">
                      <template #default="{ row }">
                        <el-button type="text" size="small" @click="viewCompanyDetail(row.id)">
                          查看详情
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>

                <el-tab-pane label="成功率分析" name="success">
                  <el-table :data="detailedStatistics.success_rates?.by_job_type || []" border style="width: 100%">
                    <el-table-column prop="job_type" label="岗位类型" />
                    <el-table-column prop="total_applications" label="总申请数" sortable />
                    <el-table-column prop="approved_applications" label="通过申请数" sortable />
                    <el-table-column prop="success_rate" label="成功率" sortable>
                      <template #default="{ row }">
                        <el-tag :type="getSuccessRateType(row.success_rate)">
                          {{ row.success_rate }}%
                        </el-tag>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 详细统计表格 -->
      <div class="detailed-statistics">
        <el-tabs v-model="activeTab2">
          <el-tab-pane label="岗位统计" name="jobs">
            <el-table :data="jobStatistics" stripe style="width: 100%">
              <el-table-column prop="status" label="状态" width="120">
                <template #default="{ row }">
                  <el-tag :type="getJobStatusTagType(row.status)">
                    {{ getJobStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="count" label="数量" width="100" />
              <el-table-column prop="percentage" label="占比" width="100">
                <template #default="{ row }">
                  {{ row.percentage }}%
                </template>
              </el-table-column>
              <el-table-column prop="description" label="说明" />
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="申请统计" name="applications">
            <el-table :data="applicationStatistics" stripe style="width: 100%">
              <el-table-column prop="status" label="状态" width="120">
                <template #default="{ row }">
                  <el-tag :type="getApplicationStatusTagType(row.status)">
                    {{ getApplicationStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="count" label="数量" width="100" />
              <el-table-column prop="percentage" label="占比" width="100">
                <template #default="{ row }">
                  {{ row.percentage }}%
                </template>
              </el-table-column>
              <el-table-column prop="description" label="说明" />
            </el-table>
          </el-tab-pane>

          <el-tab-pane label="公司统计" name="companies">
            <el-table :data="companyStatistics" stripe style="width: 100%">
              <el-table-column prop="type" label="类型" width="120" />
              <el-table-column prop="count" label="数量" width="100" />
              <el-table-column prop="percentage" label="占比" width="100">
                <template #default="{ row }">
                  {{ row.percentage }}%
                </template>
              </el-table-column>
              <el-table-column prop="description" label="说明" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  Refresh, Briefcase, Check, Document, OfficeBuilding,
  TrendCharts, Plus, DocumentAdd, Star
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { jobApi } from '@/api/jobs'

// 路由实例
const router = useRouter()

// 响应式数据
const loading = ref(false)
const activeTab = ref('popular')

// 图表引用
const jobStatusChartRef = ref()
const applicationStatusChartRef = ref()
const jobTypeChartRef = ref()
const companyTypeChartRef = ref()
const trendChartRef = ref()
const salaryChartRef = ref()
const locationChartRef = ref()
const popularJobsChartRef = ref()
const activeCompanyChartRef = ref()
const industryChartRef = ref()
const companySizeChartRef = ref()

// 趋势图时间周期
const trendPeriod = ref('month')

// 表格活跃标签
const activeTab2 = ref('jobs')

// 自动刷新相关
const autoRefresh = ref(false)
const refreshInterval = ref(30) // 秒
let refreshTimer: NodeJS.Timeout | null = null

// 统计数据
const statistics = reactive({
  jobs: {
    total: 0,
    published: 0,
    draft: 0,
    closed: 0,
    expired: 0,
    recent_30_days: 0
  },
  applications: {
    total: 0,
    pending: 0,
    approved: 0,
    rejected: 0,
    recent_30_days: 0,
    success_rate: 0
  },
  companies: {
    total: 0,
    active_companies: []
  },
  job_types: [],
  work_modes: [],
  company_types: [],
  company_sizes: [],
  industries: [],
  popular_jobs: []
})

// 详细统计数据
const jobStatistics = ref([])
const applicationStatistics = ref([])
const companyStatistics = ref([])

// 详细统计数据
const detailedStatistics = ref<any>({})

// 方法
const fetchStatistics = async () => {
  loading.value = true
  try {
    // 并行获取基础统计和详细统计
    const [basicResponse, detailedResponse] = await Promise.all([
      jobApi.getJobStatistics(),
      jobApi.getDetailedJobStatistics({ period: 'month' })
    ])

    console.log('基础统计数据:', basicResponse.data)
    console.log('详细统计数据:', detailedResponse.data)

    // 更新基础统计数据 - 确保数据结构正确
    const basicData = basicResponse.data.data || basicResponse.data
    statistics.jobs = {
      total: basicData.jobs?.total || 0,
      published: basicData.jobs?.published || 0,
      draft: basicData.jobs?.draft || 0,
      closed: basicData.jobs?.closed || 0,
      expired: basicData.jobs?.expired || 0,
      recent_30_days: basicData.jobs?.recent_30_days || 0
    }

    statistics.applications = {
      total: basicData.applications?.total || 0,
      pending: basicData.applications?.pending || 0,
      approved: basicData.applications?.approved || 0,
      rejected: basicData.applications?.rejected || 0,
      recent_30_days: basicData.applications?.recent_30_days || 0,
      success_rate: basicData.applications?.success_rate || 0
    }

    statistics.companies = {
      total: basicData.companies?.total || 0,
      active_companies: basicData.companies?.active_companies || []
    }

    // 更新分类统计数据
    statistics.job_types = basicData.job_types || []
    statistics.work_modes = basicData.work_modes || []
    statistics.company_types = basicData.company_types || []
    statistics.company_sizes = basicData.company_sizes || []
    statistics.industries = basicData.industries || []
    statistics.popular_jobs = basicData.popular_jobs || []

    // 更新详细统计数据
    detailedStatistics.value = detailedResponse.data.data || detailedResponse.data

    // 计算详细统计
    calculateDetailedStatistics()

    // 渲染图表
    await nextTick()
    renderCharts()

  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  } finally {
    loading.value = false
  }
}

const calculateDetailedStatistics = () => {
  // 岗位统计
  const jobTotal = statistics.jobs.total
  jobStatistics.value = [
    {
      status: 'published',
      count: statistics.jobs.published,
      percentage: jobTotal ? ((statistics.jobs.published / jobTotal) * 100).toFixed(1) : 0,
      description: '已发布的岗位，学生可以申请'
    },
    {
      status: 'draft',
      count: statistics.jobs.draft,
      percentage: jobTotal ? ((statistics.jobs.draft / jobTotal) * 100).toFixed(1) : 0,
      description: '草稿状态的岗位，尚未发布'
    },
    {
      status: 'closed',
      count: statistics.jobs.closed,
      percentage: jobTotal ? ((statistics.jobs.closed / jobTotal) * 100).toFixed(1) : 0,
      description: '已关闭的岗位，不再接受申请'
    },
    {
      status: 'expired',
      count: statistics.jobs.expired,
      percentage: jobTotal ? ((statistics.jobs.expired / jobTotal) * 100).toFixed(1) : 0,
      description: '已过期的岗位，需要重新发布'
    }
  ]
  
  // 申请统计
  const appTotal = statistics.applications.total
  applicationStatistics.value = [
    {
      status: 'pending',
      count: statistics.applications.pending,
      percentage: appTotal ? ((statistics.applications.pending / appTotal) * 100).toFixed(1) : 0,
      description: '等待审核的申请'
    },
    {
      status: 'approved',
      count: statistics.applications.approved,
      percentage: appTotal ? ((statistics.applications.approved / appTotal) * 100).toFixed(1) : 0,
      description: '已通过审核的申请'
    },
    {
      status: 'rejected',
      count: statistics.applications.rejected,
      percentage: appTotal ? ((statistics.applications.rejected / appTotal) * 100).toFixed(1) : 0,
      description: '已拒绝的申请'
    }
  ]

  // 更新成功率显示
  console.log('申请成功率:', statistics.applications.success_rate + '%')
}

const renderCharts = () => {
  // 岗位状态分布饼图
  if (jobStatusChartRef.value) {
    const jobStatusChart = echarts.init(jobStatusChartRef.value)
    jobStatusChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '岗位状态',
          type: 'pie',
          radius: '60%',
          data: [
            { value: statistics.jobs.published, name: '已发布', itemStyle: { color: '#67c23a' } },
            { value: statistics.jobs.draft, name: '草稿', itemStyle: { color: '#e6a23c' } },
            { value: statistics.jobs.closed, name: '已关闭', itemStyle: { color: '#f56c6c' } },
            { value: statistics.jobs.expired, name: '已过期', itemStyle: { color: '#909399' } }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  }

  // 申请状态分布饼图
  if (applicationStatusChartRef.value) {
    const applicationStatusChart = echarts.init(applicationStatusChartRef.value)
    applicationStatusChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '申请状态',
          type: 'pie',
          radius: '60%',
          data: [
            { value: statistics.applications.pending, name: '待审核', itemStyle: { color: '#e6a23c' } },
            { value: statistics.applications.approved, name: '已通过', itemStyle: { color: '#67c23a' } },
            { value: statistics.applications.rejected, name: '已拒绝', itemStyle: { color: '#f56c6c' } }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  }

  // 岗位类型分布图
  if (jobTypeChartRef.value && statistics.job_types) {
    const jobTypeChart = echarts.init(jobTypeChartRef.value)
    jobTypeChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: statistics.job_types.map((item: any) => item.job_type || '未知'),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '岗位数量',
          type: 'bar',
          data: statistics.job_types.map((item: any) => item.count),
          itemStyle: {
            color: '#409eff'
          }
        }
      ]
    })
  }

  // 公司类型分布图
  if (companyTypeChartRef.value && statistics.company_types) {
    const companyTypeChart = echarts.init(companyTypeChartRef.value)
    companyTypeChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '公司类型',
          type: 'pie',
          radius: ['40%', '70%'],
          data: statistics.company_types.map((item: any) => ({
            value: item.count,
            name: item.company_type || '未知'
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  }

  // 趋势图
  if (trendChartRef.value && detailedStatistics.value.trends) {
    const trendChart = echarts.init(trendChartRef.value)
    const jobTrends = detailedStatistics.value.trends.job_publication || []
    const appTrends = detailedStatistics.value.trends.job_applications || []

    trendChart.setOption({
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['岗位发布', '岗位申请']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: jobTrends.map((item: any) => item.date),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '岗位发布',
          type: 'line',
          smooth: true,
          data: jobTrends.map((item: any) => item.count),
          itemStyle: { color: '#409eff' }
        },
        {
          name: '岗位申请',
          type: 'line',
          smooth: true,
          data: appTrends.map((item: any) => item.count),
          itemStyle: { color: '#67c23a' }
        }
      ]
    })
  }

  // 薪资分布图
  if (salaryChartRef.value && detailedStatistics.value.distributions?.salary) {
    const salaryChart = echarts.init(salaryChartRef.value)
    const salaryData = detailedStatistics.value.distributions.salary

    salaryChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: salaryData.map((item: any) => item.range),
        axisLabel: {
          rotate: 45
        }
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '岗位数量',
          type: 'bar',
          data: salaryData.map((item: any) => item.count),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          }
        }
      ]
    })
  }

  // 地区分布图
  if (locationChartRef.value && detailedStatistics.value.distributions?.location) {
    const locationChart = echarts.init(locationChartRef.value)
    const locationData = detailedStatistics.value.distributions.location.slice(0, 10) // 取前10个

    locationChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '地区分布',
          type: 'pie',
          radius: ['40%', '70%'],
          data: locationData.map((item: any) => ({
            value: item.count,
            name: item.work_location || '未知地区'
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  }

  // 热门岗位图
  if (popularJobsChartRef.value && statistics.popular_jobs) {
    const popularJobsChart = echarts.init(popularJobsChartRef.value)
    const popularData = statistics.popular_jobs.slice(0, 10) // 取前10个

    popularJobsChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function(params: any) {
          const data = params[0]
          return `${data.name}<br/>申请数量: ${data.value}`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value'
      },
      yAxis: {
        type: 'category',
        data: popularData.map((item: any) => item.title || '未知岗位'),
        axisLabel: {
          formatter: function(value: string) {
            return value.length > 8 ? value.substring(0, 8) + '...' : value
          }
        }
      },
      series: [
        {
          name: '申请数量',
          type: 'bar',
          data: popularData.map((item: any) => item.application_count || 0),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#188df0' },
              { offset: 1, color: '#188df0' }
            ])
          }
        }
      ]
    })
  }

  // 活跃公司图
  if (activeCompanyChartRef.value && statistics.companies.active_companies) {
    const activeCompanyChart = echarts.init(activeCompanyChartRef.value)
    const activeData = statistics.companies.active_companies.slice(0, 10)

    activeCompanyChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: function(params: any) {
          const data = params[0]
          return `${data.name}<br/>发布岗位: ${data.value}个`
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'value'
      },
      yAxis: {
        type: 'category',
        data: activeData.map((item: any) => item.name || '未知公司'),
        axisLabel: {
          formatter: function(value: string) {
            return value.length > 6 ? value.substring(0, 6) + '...' : value
          }
        }
      },
      series: [
        {
          name: '发布岗位',
          type: 'bar',
          data: activeData.map((item: any) => item.total_jobs || 0),
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#ffd93d' },
              { offset: 0.5, color: '#ff9500' },
              { offset: 1, color: '#ff9500' }
            ])
          }
        }
      ]
    })
  }

  // 行业分布图
  if (industryChartRef.value && statistics.industries) {
    const industryChart = echarts.init(industryChartRef.value)
    const industryData = statistics.industries.slice(0, 8) // 取前8个

    industryChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '行业分布',
          type: 'pie',
          radius: ['40%', '70%'],
          data: industryData.map((item: any) => ({
            value: item.count,
            name: item.industry || '其他'
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  }

  // 公司规模分布图
  if (companySizeChartRef.value && statistics.company_sizes) {
    const companySizeChart = echarts.init(companySizeChartRef.value)

    companySizeChart.setOption({
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '公司规模',
          type: 'pie',
          radius: '60%',
          data: statistics.company_sizes.map((item: any) => ({
            value: item.count,
            name: item.company_size || '未知规模'
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    })
  }
}

const refreshData = () => {
  fetchStatistics()
}

// 刷新单个图表
const refreshChart = async (chartType: string) => {
  try {
    if (chartType === 'trend') {
      const response = await jobApi.getDetailedJobStatistics({ period: trendPeriod.value })
      detailedStatistics.value = response.data
    } else {
      await fetchStatistics()
    }

    await nextTick()
    renderCharts()

    ElMessage.success('图表刷新成功')
  } catch (error) {
    ElMessage.error('图表刷新失败')
  }
}

// 更新趋势图
const updateTrendChart = async () => {
  try {
    const response = await jobApi.getDetailedJobStatistics({ period: trendPeriod.value })
    detailedStatistics.value = response.data

    await nextTick()
    renderCharts()
  } catch (error) {
    ElMessage.error('更新趋势图失败')
  }
}

// 获取成功率标签类型
const getSuccessRateType = (rate: number) => {
  if (rate >= 70) return 'success'
  if (rate >= 50) return 'warning'
  return 'danger'
}

// 查看岗位详情
const viewJobDetail = (jobId: number) => {
  // 跳转到岗位详情页面
  router.push(`/jobs/${jobId}`)
}

// 查看公司详情
const viewCompanyDetail = (companyId: number) => {
  // 跳转到公司详情页面
  router.push(`/companies/${companyId}`)
}

// 导出数据
const exportData = () => {
  try {
    const data = {
      基础统计: statistics,
      详细统计: detailedStatistics.value,
      导出时间: new Date().toLocaleString()
    }

    const jsonStr = JSON.stringify(data, null, 2)
    const blob = new Blob([jsonStr], { type: 'application/json' })
    const url = URL.createObjectURL(blob)

    const link = document.createElement('a')
    link.href = url
    link.download = `岗位统计数据_${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success('数据导出成功')
  } catch (error) {
    ElMessage.error('数据导出失败')
  }
}

// 切换自动刷新
const toggleAutoRefresh = (value: boolean) => {
  if (value) {
    startAutoRefresh()
    ElMessage.success(`已开启自动刷新，间隔${refreshInterval.value}秒`)
  } else {
    stopAutoRefresh()
    ElMessage.info('已关闭自动刷新')
  }
}

// 更新刷新间隔
const updateRefreshInterval = () => {
  if (autoRefresh.value) {
    stopAutoRefresh()
    startAutoRefresh()
    ElMessage.success(`刷新间隔已更新为${refreshInterval.value}秒`)
  }
}

// 开始自动刷新
const startAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }

  refreshTimer = setInterval(() => {
    fetchStatistics()
  }, refreshInterval.value * 1000)
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 辅助方法
const getJobStatusText = (status: string) => {
  const map: Record<string, string> = {
    draft: '草稿',
    published: '已发布',
    closed: '已关闭',
    expired: '已过期'
  }
  return map[status] || status
}

const getJobStatusTagType = (status: string) => {
  const map: Record<string, string> = {
    draft: 'info',
    published: 'success',
    closed: 'warning',
    expired: 'danger'
  }
  return map[status] || 'info'
}

const getApplicationStatusText = (status: string) => {
  const map: Record<string, string> = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return map[status] || status
}

const getApplicationStatusTagType = (status: string) => {
  const map: Record<string, string> = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return map[status] || 'info'
}

// 生命周期
onMounted(() => {
  fetchStatistics()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  stopAutoRefresh()
})
</script>

<style lang="scss" scoped>
.job-statistics {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: 600;
    }

    .header-actions {
      display: flex;
      align-items: center;
      gap: 16px;

      .auto-refresh-controls {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 12px;
        background: var(--el-fill-color-light);
        border-radius: 6px;

        .el-switch {
          margin-right: 8px;
        }
      }
    }
  }

  .statistics-overview {
    margin-bottom: 30px;

    .stat-card {
      text-align: center;

      :deep(.el-statistic__content) {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
      }
    }
  }

  .charts-section {
    margin-bottom: 30px;

    .chart-card {
      .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        h3 {
          margin: 0;
          font-size: 16px;
          color: #303133;
        }

        .chart-controls {
          display: flex;
          align-items: center;
          gap: 8px;
        }
      }

      .chart-container {
        height: 300px;
        width: 100%;
      }

      .chart-container-large {
        height: 400px;
        width: 100%;
      }
    }
  }

  .detailed-statistics {
    .el-tabs {
      :deep(.el-tabs__header) {
        margin-bottom: 20px;
      }
    }
  }

  .table-card {
    margin-top: 20px;

    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 16px;
        color: #303133;
      }

      .table-controls {
        display: flex;
        gap: 8px;
      }
    }

    .el-tabs {
      margin-top: 16px;
    }

    .el-table {
      margin-top: 16px;
    }
  }
}
</style>
